package lesson.base;

import com.alibaba.fastjson.JSON;
import lesson.base.paramresolve.ParamUtil;
import lesson.permission.Role;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {


    public static final String SESSION_LOGIN_KEY = "logined";
    /**
     * 线程对应的请求
     */
    public static final ThreadLocal<HttpWrapper> threadHttp = new ThreadLocal<HttpWrapper>();

    /**
     * 跳到jsp页面
     * @param jspPath
     */
    protected void forwardJsp(String jspPath) {
        if (jspPath.endsWith(".jsp") == false) {
            jspPath += ".jsp";
        }
        try {
            getRequest().getRequestDispatcher(jspPath).forward(getRequest(), getResponse());
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void writeJSON(boolean success) throws ServletException, IOException{
        getResponse().getWriter().write(JSON.toJSONString(new Result(success)));
    }

    protected void writeJSON(boolean success, String msg) throws ServletException, IOException{
        getResponse().getWriter().write(JSON.toJSONString(new Result(success, msg)));
    }


    protected void writeJSON(boolean success, String msg, Object data) throws ServletException, IOException{
        getResponse().getWriter().write(JSON.toJSONString(new Result(success, msg, data)));
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

        HttpWrapper httpWrapper = new HttpWrapper(req, resp);
        threadHttp.set(httpWrapper);



        String uri = req.getRequestURI();

        Class clazz = this.getClass();
        WebServlet annotation = (WebServlet) clazz.getDeclaredAnnotation(WebServlet.class);
        if (annotation != null) {
            String urlPattern = annotation.value()[0];
            ///login/*   /login/
            urlPattern = urlPattern.substring(0, urlPattern.indexOf("*"));
            uri = uri.replace(urlPattern, "" );
        }

        try {
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(uri)) {

                    method.invoke(this, ParamUtil.getParamValues(getRequest(), method));

                }
            }




        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadHttp.remove();
        }




    }
    /**
     * 检查权限
     * @param method
     * @return
     */
    private boolean checkPermission(Method method) {
        Role role = method.getDeclaredAnnotation(Role.class);
        if (role == null) {
            role = method.getDeclaringClass().getDeclaredAnnotation(Role.class);
            if (role == null) {
                return false;
            }
        }
        int[] roles = role.value();
        Integer userRole = (Integer) getRequest().getSession().getAttribute(SESSION_LOGIN_KEY);
        if (userRole == null) {
            return false;
        }
        for (int r : roles) {
            if (r == userRole) {
                return true;
            }
        }

        return false;
    }
    /**
     * 获取当前线程的request实例
     * @return
     */
    protected HttpServletRequest getRequest() {
        return threadHttp.get().getRequest();
    }

    /**
     * 获取当前线程的response实例
     * @return
     */
    protected  HttpServletResponse getResponse() {
        return threadHttp.get().getResponse();
    }




}
